//
//  ViewController.m
//  VehicleNetStore
//
//  Created by xxcao on 2017/6/20.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//

#import "VNSMainViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "AppDelegate.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "NotificationManager.h"
#import "GeTuiSdk.h"
#import "SVProgressHUD.h"
#import "Common.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

typedef NS_ENUM(NSUInteger, ShareType) {
    ShareTypeWechatSession = 0,
    ShareTypeWechatTimeline,
    ShareTypeQQFriend,
    ShareTypeQZone,
    ShareTypeSinaWeibo
};

@interface VNSMainViewController ()<WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic,assign) CGFloat delayTime;
@property (nonatomic,assign) ShareType type;

@end

@implementation VNSMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    config.preferences.javaScriptEnabled = YES;
    // 交互对象设置
    [config.userContentController addScriptMessageHandler:self name:@"echarge"];
    [config.userContentController addScriptMessageHandler:self name:@"switch"];
    [config.userContentController addScriptMessageHandler:self name:@"clears"];
    [config.userContentController addScriptMessageHandler:self name:@"qqSvs"];
    [config.userContentController addScriptMessageHandler:self name:@"exitAccount"];
    // 支持内嵌视频播放，不然网页中的视频无法播放
    config.allowsInlineMediaPlayback = YES;
    
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, ScreenWidth, ScreenHeight - 20) configuration:config];
    [self.view addSubview:self.webView];
    self.webView.scrollView.delegate = self;
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    //右滑返回手势
    self.webView.allowsBackForwardNavigationGestures = YES;
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.opaque = NO;
    
    NSString *urlStr = nil;
    if (self.isFirst) {
        urlStr = kProLoginUrl;
    } else {
      urlStr = kProUrl;
    }
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [self.webView loadRequest:request];
    
    
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, ScreenWidth, 0.1)];
    [self.view addSubview:self.progressView];
    self.progressView.progressTintColor = [UIColor greenColor];
    self.progressView.trackTintColor = [UIColor clearColor];
    //
    NSKeyValueObservingOptions observingOptions = NSKeyValueObservingOptionNew;
    // KVO 监听属性，除了下面列举的两个，还有其他的一些属性，具体参考 WKWebView 的头文件
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:observingOptions context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:observingOptions context:nil];
    
    //增加推送通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsIsComing:) name:@"Notification_Key_News" object:nil];
    
    [self testMethod];
    
}

- (void)testMethod {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(ScreenWidth - 50, 30, 50, 50);
    [button setTitle:@"测试" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(shareClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });
    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    }
}


#pragma mark - WKNavigationDelegate
// 开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSLog(@"didStartProvisionalNavigation   ====    %@", navigation);
}

// 页面加载完调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"didFinishNavigation   ====    %@", navigation);
    
    if ([webView.URL.absoluteString containsString:@"myaccountNew.htm"]) {
        [self.webView evaluateJavaScript:@"initMsgIndex()" completionHandler:^(id _Nullable para, NSError * _Nullable error) {
            NSLog(@"para:%@", para);
        }];         
        if ([UserDefaultsGet(@"status") isEqualToString:@"onpush"]) {
            [self receiverMessage:YES];
        } else {
            [self receiverMessage:NO];
        }
    } else if ([webView.URL.absoluteString containsString:@"setMobileInfoOpen.htm"]) {
        NSString *status = UserDefaultsGet(@"status");
        NSString *initMethod = [NSString stringWithFormat:@"initMsg('%@')", status];
        [self.webView evaluateJavaScript:initMethod completionHandler:^(id _Nullable para, NSError * _Nullable error) {
            NSLog(@"%@", para);
        }];
    } else if ([webView.URL.absoluteString containsString:@"main.html"]) {
        //打开qq
        [self.webView evaluateJavaScript:@"initMsgQQ()" completionHandler:^(id _Nullable para, NSError * _Nullable error) {
            NSLog(@"initMsgQQ:para:%@", para);
        }];
    } else if ([webView.URL.absoluteString containsString:@"customercenter.html"]) {
        [self.webView evaluateJavaScript:@"postMsg()" completionHandler:^(id _Nullable para, NSError * _Nullable error) {
            NSLog(@"postMsg1:para%@", para);
            NSLog(@"%@", error.localizedDescription);
        }];
    }
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    [SVProgressHUD dismissWithDelay:1.5];
    NSLog(@"didFailProvisionalNavigation   ====    %@\nerror   ====   %@ %ld", navigation, error.localizedDescription, error.code);//1009
}

// 内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"didCommitNavigation   ====    %@", navigation);
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    UIApplication *app = [UIApplication sharedApplication];
    // 打电话
    if ([scheme isEqualToString:@"tel"]) {
        if ([app canOpenURL:URL]) {
            [app openURL:URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSLog(@"decidePolicyForNavigationResponse   ====    %@", navigationResponse);
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 加载 HTTPS 的链接，需要权限认证时调用  \  如果 HTTPS 是用的证书在信任列表中这不要此代理方法
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}




//MARK: - js与native交互
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@",message.body);
    if ([message.name isEqualToString:@"echarge"]) {
        // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull类型
        // 传入user_id
        NSString *userId =  [NSString stringWithFormat:@"%@", message.body[@"user_id"]];
        AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        appdelegate.userId = userId;
        
        NSLog(@"userId:%@-clientId:%@", userId, appdelegate.clientId);
        if (appdelegate.clientId.length > 0 && userId.length > 0) {
            [appdelegate uploadClient_Id];
        }
    } else if ([message.name isEqualToString:@"switch"]) {
        NSLog(@"message.body:%@",message.body);
        if ([NotificationManager isMessageNotificationServiceOpen]) {
            UserDefaultsSave(@"Yes", @"isFirst");
        } else {
            UserDefaultsSave(@"No", @"isFirst");
        }
        
        if ([UserDefaultsGet(@"isFirst") isEqualToString:@"No"]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请到系统设置打开推送" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSString * urlStr = @"App-Prefs:root=NOTIFICATIONS_ID";
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]]) {
                    if (iOS10) {
                        //iOS10.0以上  使用的操作
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
                    } else {
                        //iOS10.0以下  使用的操作
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                    }
                }
            }]];
            [self presentViewController:alert animated:YES completion:NULL];
        } else {
            UserDefaultsSave(message.body, @"status");
            if ([message.body isEqualToString:@"onpush"]) {
                [self receiverMessage:YES];
            } else {
                [self receiverMessage:NO];
            }
        }
    } else if ([message.name isEqualToString:@"clears"]) {
        [self clearCache:0];
    } else if ([message.name isEqualToString:@"qqSvs"]) {//打开qq
        NSString  *qqNumber = message.body[@"qq"];
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
            UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
            NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",qqNumber]];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            [webView loadRequest:request];
            [self.view addSubview:webView];
        } else {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"nil" message:@"对不起，您还没安装QQ" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
    } else if ([message.name isEqualToString:@"exitAccount"]) {
        //exitAccount
        [self clearCache:1];
    }
}


- (void)receiverMessage:(BOOL)receiver {
    if (receiver) {
        if (iOS10) {
            UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        } else {
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
        }
    } else {
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    }
}


//MARK: - 新资讯通知
- (void)newsIsComing:(NSNotification *)sender {
    if (![Common isEmptyString:sender.object]) {
        NSURL *url = [NSURL URLWithString:sender.object];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
    }
}

//MARK: 清除缓存
- (void)clearCache:(NSInteger)type {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes = nil;
        if (type == 0) {
            websiteDataTypes = [NSSet setWithArray:@[
                                                     WKWebsiteDataTypeDiskCache,
                                                     WKWebsiteDataTypeOfflineWebApplicationCache,
                                                     WKWebsiteDataTypeMemoryCache,
                                                     WKWebsiteDataTypeLocalStorage,
                                                     //                                                        WKWebsiteDataTypeCookies,//保留用户的账号和密码
                                                     WKWebsiteDataTypeSessionStorage,
                                                     WKWebsiteDataTypeIndexedDBDatabases,
                                                     WKWebsiteDataTypeWebSQLDatabases
                                                     ]];
        } else {
            websiteDataTypes = [NSSet setWithArray:@[
                                                     WKWebsiteDataTypeDiskCache,
                                                     WKWebsiteDataTypeOfflineWebApplicationCache,
                                                     WKWebsiteDataTypeMemoryCache,
                                                     WKWebsiteDataTypeLocalStorage,                               WKWebsiteDataTypeCookies,
                                                     WKWebsiteDataTypeSessionStorage,
                                                     WKWebsiteDataTypeIndexedDBDatabases,
                                                     WKWebsiteDataTypeWebSQLDatabases
                                                     ]];
        }
        // All kinds of data
        //        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        // Execute
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        }];
    } else {
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&error];
        if (error) {
            NSLog(@"清除失败");
        } else {
            
        }
    }
}

//MARK: 分享
- (void)shareClick {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://n1.itc.cn/img8/wb/common/2016/08/13/qianfan.png"]];
    [UIImage imageWithData:data];
    //通用参数设置
    [parameters SSDKSetupShareParamsByText:@"国网'e车城'推出定制电动车"
                                    images:[[NSBundle mainBundle] pathForResource:@"ShareIcon" ofType:@"png"]
                                       url:[NSURL URLWithString:@"http://evshome.echargenet.com/mobile/main.html"]
                                     title:@"国网电动汽车公司'e车城'推出定制电动车"
                                      type:SSDKContentTypeWebPage];
    if(parameters.count == 0){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请先设置分享参数"
                                                           delegate:nil
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    SSDKPlatformType platformType;
    switch (self.type) {
        case ShareTypeWechatSession:
            platformType = SSDKPlatformSubTypeWechatSession;
            break;
        case ShareTypeWechatTimeline:
            platformType = SSDKPlatformSubTypeWechatTimeline;
            break;
        case ShareTypeQQFriend:
            platformType = SSDKPlatformSubTypeQQFriend;
            break;
        case ShareTypeQZone:
            platformType = SSDKPlatformSubTypeQZone;
            break;
        case ShareTypeSinaWeibo:
            platformType = SSDKPlatformTypeSinaWeibo;
            break;
        default:
            break;
    }
    
    //SSDKPlatformSubTypeWechatTimeline  SSDKPlatformSubTypeWechatSession SSDKPlatformSubTypeQQFriend SSDKPlatformSubTypeQZone  SSDKPlatformTypeSinaWeibo
    [ShareSDK share:platformType
         parameters:parameters
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
         if(state == SSDKResponseStateBeginUPLoad){
             return ;
         }
         NSString *titel = @"";
         NSString *typeStr = @"";
         UIColor *typeColor = [UIColor grayColor];
         switch (state) {
             case SSDKResponseStateSuccess:
             {
                 titel = @"分享成功";
                 typeStr = @"成功";
                 typeColor = [UIColor blueColor];
                 break;
             }
             case SSDKResponseStateFail:
             {
                 NSLog(@"error :%@",error);
                 titel = @"分享失败";
                 typeStr = [NSString stringWithFormat:@"%@",error];
                 typeColor = [UIColor redColor];
                 break;
             }
             case SSDKResponseStateCancel:
             {
                 titel = @"分享已取消";
                 typeStr = @"取消";
                 break;
             }
             default:
                 break;
         }
         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titel
                                                             message:typeStr
                                                            delegate:nil
                                                   cancelButtonTitle:@"确定"
                                                   otherButtonTitles:nil];
         [alertView show];
     }];
}

/**
 js部分
 在JavaScript 将信息发给Objective-C:
 
 // window.webkit.messageHandlers.<name>.postMessage();
 
 function postMyMessage() {
 var userInfo = { 'user_id' : '3232293849544', 'user_name': 'tester'};
 window.webkit.messageHandlers.myName.postMessage(userInfo);
 }
 
 function postMyMessage(){
 var userInfo = { 'user_id' : '3232293849544', 'user_name': 'tester'};
 window.name.jsMethod(userInfo);
 }
 */

@end
